import grails.converters.*
import org.hibernate.FetchMode

class PictureController {
	def index = { redirect(action:list,params:params) }

    // the delete, save and update actions only accept POST requests
    def allowedMethods = [delete:'POST', save:'POST', update:'POST']

    def list = {
        if(session.authenticatedUser == null) {
          	redirect(controller:'authentication',action:'index')	
        }
       	if (session.userCart == null) {
       		session.userCart = ""
       	}	
   		// Display list.gsp
    }
    
    def extList = {
       def list;
       def title = ""
       if(params.user) {
    	   def AuthenticationService authenticationService = new AuthenticationService()
    	   def user = authenticationService.getAuthenticationUser(session.authenticatedUser)
    	   list = user.pictures
    	   title = "My Pictures"
       } else if(params.category != null) {
    	   list = Picture.findAllWhere(category: params.category)
    	   title = "Category: " + Category.toCategory(params.category).getDisplayValue(Locale.US)
       } else {
    	   list = Picture.list();
    	   title = "All Pictures"
       }
        
       def listResult =  [ title: title, total: Picture.count(), pictureList: list ]
       render listResult as JSON 
    }

    
    def userList = {

    }
    
    def show = {
        def pictureInstance = Picture.get( params.id )
        if(!pictureInstance) {
            flash.message = "Picture not found with id ${params.id}"
            redirect(action:list)
        }
        else { 
        	def pictureResult =  [ success : true, data : pictureInstance ]
        	render pictureResult as JSON
        }        
    }

    def delete = {
    	def pictureInstance = Picture.get( params.pictureId )
        def isSuccess = true;
        if (pictureInstance) {
            //Delete image file
            String path = pictureInstance.imagePath
            String tmpName = (new File(pictureInstance.getFilenameAndExtension(path))).getAbsoluteFile()
            String dirName = pictureInstance.MyLeftStr(tmpName,pictureInstance.getFilenameAndExtension(path))
            File file1 = new File(dirName + pictureInstance.getLongPath(path))
            if (file1.exists()) {
            	isSuccess = file1.delete()
    	    }
    	    //Delete thumbnail file
            path = pictureInstance.thumbnailPath
            tmpName = (new File(pictureInstance.getFilenameAndExtension(path))).getAbsoluteFile()
            dirName = pictureInstance.MyLeftStr(tmpName,pictureInstance.getFilenameAndExtension(path))
            File file2 = new File(dirName + pictureInstance.getLongPath(path))
            if (file2.exists()) {
            	isSuccess = file2.delete()
    	    }
            isSuccess = pictureInstance.delete()            
        }
        def response = [ success: isSuccess ]
        def json = response as JSON
        render json.toString()
    }

    def update = {
        def pictureInstance = Picture.get( params.id )
        def response = [ success: false ]
        if(pictureInstance) {
            pictureInstance.name = params.name
            pictureInstance.description = params.description
            pictureInstance.price = params.price as Double
            //pictureInstance.setCategory(Category.toCategory(params.category))
            def hasErrors = pictureInstance.hasErrors()
            def isSaved = pictureInstance.save()
            if(!hasErrors && isSaved) {
            	response = [ success: true, data : pictureInstance]
            }
        }
        def json = response as JSON
        render json.toString()
    }
    
    def save = {
        def AuthenticationService authenticationService = new AuthenticationService()
        def pictureInstance = new Picture(params)
        String fileName = System.currentTimeMillis().toString()
        pictureInstance.setImagePath(request.getFile("file").getBytes(), fileName)
        pictureInstance.user = authenticationService.getAuthenticationUser(session.authenticatedUser)
        def response = [ success: false ]
        if(!pictureInstance.hasErrors() && pictureInstance.save()) {
        	response = [ success: true, data : pictureInstance]
        }
        def json = response as JSON
    	render json.toString()
   }
    
   def categories = {
       def response = [rows: Category.getCategoryMap(Locale.US)]
       render response as JSON
   }
    
   def categoryActions = {

   }
}
